﻿
namespace MoneyBook.Web.Services {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using MoneyBook.Web.Models;
    using System.Data.Objects;


    // Implements application logic using the MoneyBookEntities context.
    // TODO: Add your application logic to these methods or in additional methods.
    // TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
    // Also consider adding roles to restrict access as appropriate.
    // [RequiresAuthentication]
    [EnableClientAccess()]
    public class AccountService : LinqToEntitiesDomainService<MoneyBookEntities> {

        // TODO:
        // Consider constraining the results of your query method.  If you need additional input you can
        // add parameters to this method or create additional query methods with different names.
        // To support paging you will need to add ordering to the 'Accounts' query.
        public IQueryable<Account> GetAccounts() {
            return this.ObjectContext.Accounts.OrderBy(a => a.AccountId);
        }

        [Query]
        public IQueryable<Account> GetAccountsByMember(int memberId) {
            var accountsQuery = (from a in this.ObjectContext.Accounts
                                 join am in this.ObjectContext.AccountMembers on a.AccountId equals am.AccountId
                                 where am.MemberId == memberId
                                 select a) as ObjectQuery<Account>;

            return accountsQuery.Include("Categories");
        }
        

        public Account FindAccount(int memberId, string accountName) {
            return this.GetAccountsByMember(memberId).Where(am => am.AccountName == accountName).FirstOrDefault();
        }

        public void AddAccount(Account account) {
            if ((account.EntityState != EntityState.Detached)) {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(account, EntityState.Added);
            } else {
                account.AccountMembers.Add(new AccountMember(){
                    MemberId = account.OwnerId
                });
               
                this.ObjectContext.Accounts.AddObject(account);
                this.ObjectContext.SaveChanges();

                foreach (Category category in this.CreateDefaultCategories()) {
                    account.Categories.Add(category);
                }

                Member member = this.ObjectContext.Members.First(m => m.MemberId == account.OwnerId);
                if (!member.MainAccountId.HasValue) {
                    member.MainAccount = account;
                }

                this.ObjectContext.SaveChanges();
            }
        }

        private List<Category> CreateDefaultCategories() {
            List<Category> categories = new List<Category>();
            foreach (string name in new string[] { "書籍", "食料", "日用品", "衣料品", "娯楽", "外食" }) {
                categories.Add(new Category() { CategoryName = name });
            }
            return categories;
        }

        //public void UpdateAccount(Account currentAccount) {
        //    this.ObjectContext.Accounts.AttachAsModified(currentAccount, this.ChangeSet.GetOriginal(currentAccount));
        //}

        //public void DeleteAccount(Account account) {
        //    if ((account.EntityState == EntityState.Detached)) {
        //        this.ObjectContext.Accounts.Attach(account);
        //    }
        //    this.ObjectContext.Accounts.DeleteObject(account);
        //}
    }
}


